package com.zrq.core.mail;

import com.zrq.core.props.Props;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.validation.annotation.Validated;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * @Author: zrq
 * @CreateDate: 2020/11/18
 * @Version: 类说明： 邮件发送类
 */
@Configuration
@Slf4j
@AllArgsConstructor
@Validated
public class MailSendService {

    private final JavaMailSenderImpl javaMailSender;

    private final Props props;

    /**
     * 发送邮件,含图片的形式可以使用html的格式img标签中
     * @param ToMail 收件人
     * @param title 邮件标题
     * @param content 邮件内容
     * @param isHtml 是否是html格式
     * @throws MessagingException
     */
    public void sendMessage(String ToMail,String title,String content,Boolean isHtml) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
        mimeMessageHelper.setTo(ToMail);
        mimeMessageHelper.setFrom(props.getUsername());
        mimeMessageHelper.setSubject(title);
        // 启用html
        mimeMessageHelper.setText(content, isHtml);
        // 发送邮件
        log.info("邮件发送中----------");
        javaMailSender.send(mimeMessage);

    }


    /**
     * 发送包含附件的邮件
     * @param file 文件
     * @param toSend 接收者
     * @param title 标题
     * @throws MessagingException
     */
    /**
     * 发送包含附件的邮件
     * @param file 文件
     * @param toSend 接收者
     * @param title 标题
     * @param content 邮件内容
     * @param isHtml 是否是HTML文件
     * @throws MessagingException
     */
    public void sendFileMessage(File file,String toSend,String title,String content,Boolean isHtml) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //创建邮件助手
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
        mimeMessageHelper.setFrom(props.getUsername());
        mimeMessageHelper.setTo(toSend);
        //设置标题
        mimeMessageHelper.setSubject(title);
        //邮件内容
        mimeMessageHelper.setText(content,isHtml);

        //设置附件文件
        FileSystemResource fileSystemResource = new FileSystemResource(file);
        mimeMessageHelper.addAttachment(file.getAbsoluteFile().getName(),fileSystemResource);

        //发送邮件
        log.info("邮件附件发送中----------");
        javaMailSender.send(mimeMessage);

    }

}
